//
//  DiaryMapView.swift
//  MyDiary2025
//
//  Created by 罗万能 on 2025/6/27.
//

import SwiftUI
import MapKit

struct DiaryMapView: View {
    @State var mapCameraPosition : MapCameraPosition = .region(MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 30, longitude: 104), span: MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02)))
    @State var scaleNum = 0.001
    var diary: DiaryModel
    var body: some View {
        Map(position:  $mapCameraPosition) {
            if diary.location != nil{
                Marker(coordinate: diary.location!) {
                    Text(diary.locationDescription)
                }
                
            }
            
        }
        .onAppear(perform: {
            setCameraPosition()
        })
        .mapControlVisibility(.hidden)
       
        .overlay(alignment: .bottomTrailing) {
            
            Stepper() {
                EmptyView()
            }onIncrement: {
                withAnimation{
                    if self.scaleNum - 0.005 >= 0.0001{
                        self.scaleNum -= 0.005
                    }
                    
                }
            } onDecrement: {
                withAnimation{
                    if self.scaleNum + 0.005 < 10{
                        self.scaleNum += 0.005
                    }
                }
            }
        }
        .onChange(of: scaleNum) { oldValue, newValue in
            setCameraPosition()
        }
    }
    private func setCameraPosition(){
        var location =  CLLocationCoordinate2D(latitude: 30.657413, longitude: 104.064773)
        if diary.latitude != nil && diary.longitude != nil{
            location.longitude = diary.longitude!
            location.latitude = diary.latitude!
        }
        let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude), span: MKCoordinateSpan(latitudeDelta: scaleNum, longitudeDelta: scaleNum))
        self.mapCameraPosition = MapCameraPosition.region(region)
    }
}

#Preview {
    DiaryMapView( diary: DiaryModel.debugData)
}
